﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;

namespace Protocal.App.Common
{
    public class AppSetting
    {
        private static IConfigurationRoot _config;

        static AppSetting()
        {
            _config = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json",false, true)
                .Build();
        }

        /// <summary>
        /// 获取配置项的值
        /// </summary>
        public static T Get<T>(params string[] keys)
        {
            try
            {
                if (keys.Length == 1)
                {
                    return _config.GetSection(keys[0]).Get<T>();
                }
                else
                {
                    // _config.GetSection("Logging").GetSection("LogLevel").GetValue<string>("Default")
                    string key = keys[keys.Length - 1];
                    string prefix = string.Join(":", keys.Take(keys.Length - 1));
                    return _config.GetSection(prefix).GetValue<T>(key);
                }
            }
            catch
            {
                return default(T);
            }
        }

        /// <summary>
        /// 获取指定 section 下的整个对象绑定（适用于配置模型类）
        /// </summary>
        public static T GetSection<T>(string sectionName) where T : new()
        {
            var section = new T();
            _config.GetSection(sectionName).Bind(section);
            return section;
        }
    }
}
